<?php


namespace app\common\repositories\system\poster;

use app\common\dao\system\poster\PosterDao;
use app\common\repositories\BaseRepository;
use FormBuilder\Factory\Elm;
use think\exception\ValidateException;
use think\facade\Route;

class PosterRepository extends BaseRepository
{
    public function __construct(PosterDao $dao)
    {
        $this->dao = $dao;
    }


    public function getList(array $where, int $page, int $limit)
    {
        $query = $this->dao->getSearch($where)->order('create_at DESC');
        $count = $query->count();
        $list = $query->page($page, $limit)->select();
        return compact('count','list');
    }

    public function form(?int $id)
    {
        if ($id) {
            $formData = $this->dao->get($id)->toArray();
            $form = Elm::createForm(Route::buildUrl( 'systemPosterUpdate', ['id' => $id])->build());
        } else {
            $form = Elm::createForm(Route::buildUrl('systemPosterCreate' )->build());
            $formData = [];
        }
        $form->setRule([
            Elm::frameImage('img', '图片', '/' . config('admin.admin_prefix') . '/setting/uploadPicture?field=img&type=1')->width('1000px')->height('600px')->props(['footer' => false])->modal(['modal' => false, 'custom-class' => 'suibian-modal']),
            Elm::number('sort', '排序', 0)->precision(0)->max(99999),
        ]);
        return $form->setTitle(is_null($id) ? '添加' :  '编辑')->formData($formData);
    }

    public function getSonCategoryList($type,$pid = 0)
    {
        $where['pid'] = $pid;
        $where['is_mer'] = $type;
        if($type == 1){
            $where['not_type'] = 'product_category';
        }
        $list = $this->dao->getSearch($where)->where('level','<',3)
            ->field( 'id,pid,type,name label,status')->order('sort DESC,add_time DESC')->select();
        $arr = [];
        if ($list) {
            foreach ($list as $item) {
                if($item['status'] == 1){
                    $item['title'] = $item['label'];
                    $item['expand'] = true;
                    $item['children'] = $this->getSonCategoryList($type,$item['id']);
                    $arr [] = $item;
                }
            }
        }
        return $arr;
    }

}
